package com.example.servlet;

import com.example.dao.EmployeeDao;
import com.example.entity.Employee;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 员工管理Servlet，处理员工相关请求
 */
@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(EmployeeServlet.class.getName());
    private EmployeeDao employeeDao = new EmployeeDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        if (action == null) {
            action = "list";
        }

        try {
            switch (action) {
                case "list":
                    listEmployees(req, resp);
                    break;
                case "add":
                    req.getRequestDispatcher("addEmployee.jsp").forward(req, resp);
                    break;
                case "edit":
                    getEmployee(req, resp);
                    break;
                case "delete":
                    deleteEmployee(req, resp);
                    break;
                default:
                    listEmployees(req, resp);
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error handling employee request", e);
            req.setAttribute("errorMessage", "操作失败: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");

        try {
            switch (action) {
                case "add":
                    addEmployee(req, resp);
                    break;
                case "update":
                    updateEmployee(req, resp);
                    break;
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Error handling employee request", e);
            req.setAttribute("errorMessage", "操作失败: " + e.getMessage());
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
        }
    }

    private void listEmployees(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Employee> employees = employeeDao.getAllEmployees();
        if (employees.isEmpty()) {
            LOGGER.warning("Warning: Employee list is empty");
        }
        req.setAttribute("employees", employees);
        req.getRequestDispatcher("employeeList.jsp").forward(req, resp);
    }

    private void addEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        int age = 0;
        int departmentId = 0;
        try {
            age = Integer.parseInt(req.getParameter("age"));
            departmentId = Integer.parseInt(req.getParameter("department_id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for age or departmentId", e);
            req.setAttribute("errorMessage", "年龄或部门 ID 输入无效");
            req.getRequestDispatcher("addEmployee.jsp").forward(req, resp);
            return;
        }
        String position = req.getParameter("position");
        String hireDate = req.getParameter("hire_date");

        Employee employee = new Employee();
        employee.setName(name);
        employee.setGender(gender);
        employee.setAge(age);
        employee.setDepartmentId(departmentId);
        employee.setPosition(position);
        employee.setHireDate(hireDate);

        employeeDao.addEmployee(employee);

        resp.sendRedirect("employee?action=list");
    }

    private void getEmployee(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int employeeId = 0;
        try {
            employeeId = Integer.parseInt(req.getParameter("id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for employeeId", e);
            req.setAttribute("errorMessage", "员工 ID 输入无效");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        Employee employee = employeeDao.getEmployeeById(employeeId);
        req.setAttribute("employee", employee);
        req.getRequestDispatcher("editEmployee.jsp").forward(req, resp);
    }

    private void deleteEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        int employeeId = 0;
        try {
            employeeId = Integer.parseInt(req.getParameter("id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for employeeId", e);
            req.setAttribute("errorMessage", "员工 ID 输入无效");
            try {
                req.getRequestDispatcher("/error.jsp").forward(req, resp);
            } catch (ServletException ex) {
                throw new RuntimeException(ex);
            }
            return;
        }
        employeeDao.deleteEmployee(employeeId);
        resp.sendRedirect("employee?action=list");
    }

    private void updateEmployee(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        int id = 0;
        int age = 0;
        int departmentId = 0;
        try {
            id = Integer.parseInt(req.getParameter("id"));
            age = Integer.parseInt(req.getParameter("age"));
            departmentId = Integer.parseInt(req.getParameter("department_id"));
        } catch (NumberFormatException e) {
            LOGGER.log(Level.SEVERE, "Invalid input for id, age or departmentId", e);
            req.setAttribute("errorMessage", "ID、年龄或部门 ID 输入无效");
            req.getRequestDispatcher("/error.jsp").forward(req, resp);
            return;
        }
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String position = req.getParameter("position");
        String hireDate = req.getParameter("hire_date");

        Employee employee = new Employee();
        employee.setId(id);
        employee.setName(name);
        employee.setGender(gender);
        employee.setAge(age);
        employee.setDepartmentId(departmentId);
        employee.setPosition(position);
        employee.setHireDate(hireDate);

        employeeDao.updateEmployee(employee);

        resp.sendRedirect("employee?action=list");
    }
}